package com.lbiuse.wx.api;

import java.util.ArrayList;
import java.util.List;

import com.lbiuse.wx.bean.group.Group;
import com.lbiuse.wx.util.WxHttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;



/**
 * 用户组API
 * 
 * @author jinglupeng.cc
 */
public class GroupAPI {

	private static Logger logger = Logger.getLogger(GroupAPI.class);

	private final static String CREATE_GROUP_URL = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN";
	private final static String GET_GROUPS_URL = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=ACCESS_TOKEN";
	private final static String GET_USER_GROUP_ID_URL = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=ACCESS_TOKEN";
	private final static String UPDATE_GROUP_URL = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN";
	private final static String MOVE_MEMBER_GROUP_URL = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=ACCESS_TOKEN";

	/**
	 * 创建分组
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param name
	 *            -分组名字（30个字符以内）
	 * @return
	 */
	public static Group createGroup(String appId, String name) {
		if (name == null || name.length() <= 0 || name.length() >= 30) {
			logger.error("创建分组失败，分组名称必须在30个字符以内, 分组名称:" + name);
			return null;
		}
		JSONObject json1 = new JSONObject();
		JSONObject json2 = new JSONObject();
		json2.put("name", name);
		json1.put("group", json2);

		String json = json1.toString();
		logger.info(json);
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("创建分组失败, 获取AccessToken失败!");
			return null;
		}
		String url = CREATE_GROUP_URL.replace("ACCESS_TOKEN", token);
		try {
			json = WxHttpUtils.post(url, json);
			JSONObject jsonObject = JSONObject.fromObject(json);
			if (jsonObject.containsKey("errcode")) {
				int errcode = jsonObject.getInt("errcode");
				if (errcode != 0) {
					logger.error("创建分组失败，错误码：" + errcode);
					return null;
				}
			}
			jsonObject = jsonObject.getJSONObject("group");
			String id = jsonObject.getString("id");
			name = jsonObject.getString("name");
			Group group = new Group();
			group.setCount(0l);
			group.setId(id);
			group.setName(name);
			return group;
		} catch (Exception e) {
			logger.error("创建分组失败, 错误信息:" + e.getMessage());
			return null;
		}
	}

	/**
	 * 查询所有分组
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @return
	 */
	public static List<Group> getGroups(String appId) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("创建分组失败, 获取AccessToken失败!");
			return null;
		}
		String url = GET_GROUPS_URL.replace("ACCESS_TOKEN", token);
		try {
			String json = WxHttpUtils.get(url);
			JSONObject jsonObject = JSONObject.fromObject(json);
			if (jsonObject.containsKey("errcode")) {
				int errcode = jsonObject.getInt("errcode");
				if (errcode != 0) {
					logger.error("查询分组列表失败，错误码：" + errcode);
					return null;
				}
			}
			JSONArray jsonArray = jsonObject.getJSONArray("groups");
			List<Group> groups = new ArrayList<Group>();
			int length = jsonArray.size();
			for (int i = 0; i < length; i++) {
				jsonObject = jsonArray.getJSONObject(i);
				Group group = new Group();
				group.setCount(jsonObject.getLong("count"));
				group.setId(jsonObject.getString("id"));
				group.setName(jsonObject.getString("name"));
				groups.add(group);
			}
			return groups;
		} catch (Exception e) {
			logger.error("查询所有分组失败, 错误信息:" + e.getMessage());
			return null;
		}
	}

	/**
	 * 查询用户所在分组
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param openId
	 *            -用户的OpenID
	 * @return
	 */
	public static String getUserGroupId(String appId, String openId) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("创建分组失败, 获取AccessToken失败!");
			return null;
		}
		String url = GET_USER_GROUP_ID_URL.replace("ACCESS_TOKEN", token);
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("openid", openId);
			String json = jsonObject.toString();
			json = WxHttpUtils.post(url, json);
			jsonObject = JSONObject.fromObject(json);
			if (jsonObject.containsKey("errcode")) {
				int errcode = jsonObject.getInt("errcode");
				if (errcode != 0) {
					logger.error("查询用户所在分组失败，错误码：" + errcode);
					return null;
				}
			}
			return jsonObject.getString("groupid");
		} catch (Exception e) {
			logger.error("查询用户所在分组失败, 错误信息:" + e.getMessage());
			return null;
		}
	}

	/**
	 * 修改分组名
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param group
	 *            -分组信息
	 * @return
	 */
	public static boolean updateGroup(String appId, Group group) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("创建分组失败, 获取AccessToken失败!");
			return false;
		}
		String url = UPDATE_GROUP_URL.replace("ACCESS_TOKEN", token);
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("group", group);
			String json = jsonObject.toString();
			json = WxHttpUtils.post(url, json);
			jsonObject = JSONObject.fromObject(json);
			int errcode = jsonObject.getInt("errcode");
			if (errcode == 0) {
				return true;
			}
			logger.error("修改分组名称失败，错误码：" + errcode);
			return false;
		} catch (Exception e) {
			logger.error("修改分组名称失败, 错误信息:" + e.getMessage());
			return false;
		}
	}

	/**
	 * 移动用户分组
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param openId
	 *            -用户唯一标识符
	 * @param groupId
	 *            -分组id
	 * @return
	 */
	public static boolean moveMemberGroup(String appId, String openId,
			String groupId) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("移动用户分组失败, 获取AccessToken失败!");
			return false;
		}
		String url = MOVE_MEMBER_GROUP_URL.replace("ACCESS_TOKEN", token);
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("openid", openId);
			jsonObject.put("to_groupid", groupId);
			String json = jsonObject.toString();
			json = WxHttpUtils.post(url, json);
			jsonObject = JSONObject.fromObject(json);
			int errcode = jsonObject.getInt("errcode");
			if (errcode == 0) {
				return true;
			}
			logger.error("移动用户分组失败，错误码：" + errcode);
			return false;
		} catch (Exception e) {
			logger.error("移动用户分组失败, 错误信息:" + e.getMessage());
			return false;
		}
	}
}
